package com.yiya.ms.action;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.Company;
import com.yiya.bean.CompanyUserInfo;
import com.yiya.bean.Employee;
import com.yiya.bean.SerOrderInfo;
import com.yiya.bean.SysUser;
import com.yiya.model.SerOrderInfoCplex;
import com.yiya.model.SerOrderInfoCplexModel;
import com.yiya.service.CompanyService;
import com.yiya.service.CompanyUserInfoService;
import com.yiya.service.EmployeeService;
import com.yiya.service.SerOrderInfoService;
import com.yiya.service.SysRoleService;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.PinyinUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/orderInfo")
public class SerOrderInfoAction extends BaseAction{
	@SuppressWarnings("unused")
	private final static Logger log= Logger.getLogger(SerOrderInfoAction.class);

	@Autowired
	private SerOrderInfoService serOrderInfoService;
	
	@Autowired
	private CompanyUserInfoService companyUserInfoService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private EmployeeService employeeService;
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private SysRoleService sysRoleService;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }
		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        
		});
	}
	
	@RequestMapping("/list") 
	public ModelAndView list(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("orderInfo/orderInfo",context); 
	}
	
	@RequestMapping("/dataList") 
	public void  datalist(SerOrderInfoCplexModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		int scope = sysRoleService.queryUserViewScope(user.getId());
		if(user!=null&&user.getSuperAdmin()!=1){
			if(scope!=1){
				//只看自己相关的
				model.setCreateBy(user.getId());
			}else{
				//获取所属公司相关的
				CompanyUserInfo userInfo = companyUserInfoService.queryByUserId(user.getId());
				if(userInfo!=null){
					model.setCompanyId(userInfo.getCompanyId());
				}
			}
		}
		
		List<SerOrderInfoCplex> list = serOrderInfoService.queryByList(model);
		int count = serOrderInfoService.queryByCount(model);
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
		
	}
	
	@RequestMapping("/save")
	public void save(SerOrderInfo bean,HttpServletRequest request,HttpServletResponse response){
		SysUser user = SessionUtils.getUser(request);
		
		Date nowTime = new Date();
		if(bean.getId() == null){
			CompanyUserInfo companyUserInfo = companyUserInfoService.queryByUserId(user.getId());
			Company company = companyService.queryById(companyUserInfo.getCompanyId());
			bean.setUserId(companyUserInfo.getId());
			bean.setCompanyId(companyUserInfo.getCompanyId());
			bean.setSerCompanyId(company.getSerCompanyId());//设置处理该维修单的维修公司id
			bean.setOrderStatus(0);//将维修单状态设置为已申请
			bean.setCreateBy(user.getId());
			bean.setCreateTime(nowTime);
			bean.setRepairType(0);
			serOrderInfoService.add(bean);
		}else{
			bean.setUpdateBy(user.getId());
			bean.setUpdateTime(nowTime);
			serOrderInfoService.Update(bean);
		}
		sendSuccessMessage(response, "保存成功");
	}
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response){
		Map<String,Object>  context = getRootMap();
		SerOrderInfo bean = serOrderInfoService.queryById(id);
		if(bean  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/initOrder")
	public void initOrder(Integer id,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object>  context = getRootMap();
		SysUser user = SessionUtils.getUser(request);
		CompanyUserInfo companyUserInfo = companyUserInfoService.queryByUserId(user.getId());
		int UnfinishedOrderCount = serOrderInfoService.getUnfinishedOrderCount(user.getId());
		if(UnfinishedOrderCount==0){
			if(companyUserInfo!=null){
				Company company = companyService.queryById(companyUserInfo.getCompanyId());
				SerOrderInfo bean = new SerOrderInfo();
				
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				String nowTime = format.format(new Date());
				String number = PinyinUtil.cn2py(company.getName()).toUpperCase()+nowTime;
				bean.setNumber(number);
				
				
				context.put(SUCCESS, true);
				context.put("data", bean);
				HtmlUtil.writerJson(response, context);
			}else{
				sendFailureMessage(response, "您的账号没有与公司绑定!");
			}
		}else{
			sendFailureMessage(response, "您还有进行中的维修单，不能发起新的申请!");
		}
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		serOrderInfoService.delete(id,user);
		sendSuccessMessage(response, "删除成功");
	}
	
	/**
	 * 维修公司管理员页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/serCompanyList") 
	public ModelAndView serCompanyList(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("orderInfo/serCompany_orderInfo",context); 
	}
	
	/**
	 * 维修公司管理员看到的维修单数据
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/serCompanyDataList") 
	public void  serCompanyDataList(SerOrderInfoCplexModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		if(user.getSuperAdmin()!=1){
			Employee employee = employeeService.queryByUserId(user.getId());
			model.setSerCompanyId(employee.getSerCompanyId());//只获取跟该公司关联的维修单
		}
		List<SerOrderInfoCplex> list = serOrderInfoService.queryByList(model);
		int count = serOrderInfoService.queryByCount(model);
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
	}
	
	/**
	 * 保存派单信息
	 * @param bean
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveSendOrderInfo")
	public void saveSendOrderInfo(SerOrderInfo bean,HttpServletRequest request,HttpServletResponse response){
		Company company = companyService.queryById(bean.getCompanyId());
		if(company!=null&&company.getState()==1){
			SysUser user = SessionUtils.getUser(request);
			Date nowTime = new Date();
			SerOrderInfo info = new SerOrderInfo();
			info.setId(bean.getId());
			info.setEmployeeId(bean.getEmployeeId());
			info.setOrderStatus(6);//设为已接单
			info.setUpdateBy(user.getId());
			info.setUpdateTime(nowTime);
			serOrderInfoService.Update(info);
			sendSuccessMessage(response, "保存成功");
		}else{
			sendFailureMessage(response, "该公司已过期，派单请续费！");
		}
	}
	
	@RequestMapping("/employeeList") 
	public ModelAndView employeeList(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("orderInfo/employee_orderInfo",context); 
	}
	
	/**
	 * 维修公司维修员看到的维修单数据
	 * @param model
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/employeeDataList") 
	public void  employeeDataList(SerOrderInfoCplexModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		int scope = sysRoleService.queryUserViewScope(user.getId());
		
		model.setOrderStatus(6);
		if(user.getSuperAdmin()!=1){
			Employee employee = employeeService.queryByUserId(user.getId());
			model.setSerCompanyId(employee.getSerCompanyId());//只获取跟该公司关联的维修单
			if(scope!=1){
				if(model.getEmployee()!=null){
					model.getEmployee().setId(employee.getId());//只获取跟该维修员相关的维修单
				}else{
					Employee e = new Employee();
					e.setId(employee.getId());
					model.setEmployee(e);
				}
			}
		}
		
		List<SerOrderInfoCplex> list = serOrderInfoService.queryByList(model);
		int count = serOrderInfoService.queryByCount(model);
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
	}
	
	/**
	 * 保存维修结果信息
	 * @param bean
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveRepairResultOrderInfo")
	public void saveRepairResultOrderInfo(SerOrderInfo bean,HttpServletRequest request,HttpServletResponse response){
		SysUser user = SessionUtils.getUser(request);
		Date nowTime = new Date();
		SerOrderInfo info = new SerOrderInfo();
		info.setId(bean.getId());
		info.setOrderStatus(12);//设为已维修
		info.setCurrentResult(bean.getCurrentResult());
		info.setUpdateBy(user.getId());
		info.setUpdateTime(nowTime);
		serOrderInfoService.Update(info);
		sendSuccessMessage(response, "保存成功");
	}
	
	@RequestMapping("/hasNotCommentList") 
	public ModelAndView hasNotCommentList(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("orderInfo/has_not_comment_orderInfo",context); 
	}
	
	/**
	 * 未评价的维修单数据
	 * @param model
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/hasNotCommentDataList") 
	public void  hasNotCommentDataList(SerOrderInfoCplexModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		
		List<SerOrderInfoCplex> list = null;
		int count = 0;
		
		model.setOrderStatus(12);//已维修待反馈的维修记录
		if(user.getSuperAdmin()==1){
			list = serOrderInfoService.queryByList(model);
			count = serOrderInfoService.queryByCount(model);
		}else{
			int scope = sysRoleService.queryUserViewScope(user.getId());
			CompanyUserInfo userInfo = companyUserInfoService.queryByUserId(user.getId());
			if(scope==1){
				model.setCompanyId(userInfo.getCompanyId());
			}else{
				model.setCreateBy(user.getId());
			}
			list = serOrderInfoService.queryByList(model);
			count = serOrderInfoService.queryByCount(model);
		}
		
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
		
	}
	
	/**
	 * 保存用户评价
	 * @param bean
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveComment")
	public void saveComment(SerOrderInfo bean,HttpServletRequest request,HttpServletResponse response){
		SysUser user = SessionUtils.getUser(request);
		Date nowTime = new Date();
		SerOrderInfo info = new SerOrderInfo();
		if(bean.getUserFeedback()==0){
			SerOrderInfo orderInfo = serOrderInfoService.queryById(bean.getId());
			
			info.setId(bean.getId());
			info.setRepairType(1);
			info.setOrderStatus(6);
			info.setHistoryRecord(orderInfo.getCurrentResult());
			info.setCurrentResult("");
			info.setUserFeedback(null);
			info.setUserOpinion("");
			info.setRepairTimes(bean.getRepairTimes()==null?1:bean.getRepairTimes()+1);
			info.setUpdateBy(user.getId());
			info.setUpdateTime(nowTime);
			serOrderInfoService.Update(info);
		}else{
			info.setId(bean.getId());
			info.setOrderStatus(30);//设为已结束
			info.setUserFeedback(bean.getUserFeedback());
			info.setUserOpinion(bean.getUserOpinion());
			info.setUpdateBy(user.getId());
			info.setUpdateTime(nowTime);
			serOrderInfoService.Update(info);
		}
		
		sendSuccessMessage(response, "保存成功");
	}
	
	/**
	 * 维修历史纪录
	 * @param request
	 * @return
	 */
	@RequestMapping("/history_list") 
	public ModelAndView historyList(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("orderInfo/orderInfo_history",context); 
	}
	
	@RequestMapping("/history_dataList") 
	public void  historyDatalist(SerOrderInfoCplexModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{
SysUser user = SessionUtils.getUser(request);
		
		List<SerOrderInfoCplex> list = null;
		int count = 0;
		
		if(user.getSuperAdmin()==1){
			list = serOrderInfoService.queryByList(model);
			count = serOrderInfoService.queryByCount(model);
		}else{
			int scope = sysRoleService.queryUserViewScope(user.getId());
			Employee employee = employeeService.queryByUserId(user.getId());
			if(scope==1){
				model.setSerCompanyId(employee.getSerCompanyId());
			}else{
				model.setEmployee(employee);
			}
			list = serOrderInfoService.queryByList(model);
			count = serOrderInfoService.queryByCount(model);
		}
		
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
		
	}
}
